﻿using CommonBase;
using CommonBase.ResponseBase;
using CustomControls.PoptipCtr.Base;
using CustomControls.PoptipCtr;
using LogProjectManager;
using MyAppProjectControl.BaseViewModels;
using MyAppProjectControl.Model;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Ioc;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Security.Policy;
using System.Net.Http.Headers;
using Prism.Regions;

namespace MyAppProjectControl.ViewModels
{
    public class IndexPageViewModel : BaseViewModel
    {

        private string LastSelectDevId { set; get; }
        private string LastSelectFileId { set; get; }
        private Dictionary<int, int> CurrentItemIndex { set; get; }

        private DeviceDbModel _SelectDeviceModel;

        public DeviceDbModel SelectDeviceModel
        {
            get { return _SelectDeviceModel; }
            set { SetProperty(ref _SelectDeviceModel, value); }
        }

        private ObservableCollection<DeviceDbModel> _DeviceList;

        public ObservableCollection<DeviceDbModel> DeviceList
        {
            get { return _DeviceList; }
            set { SetProperty(ref _DeviceList, value); }
        }

      

      
        #region cmd
        private DelegateCommand<int?> _PageUpdatedCommand;
        public DelegateCommand<int?> PageUpdatedCommand =>
            _PageUpdatedCommand ?? (_PageUpdatedCommand = new DelegateCommand<int?>(ExecutePageUpdatedCommand));

        /// <summary>
        /// 维护
        /// </summary>
        private DelegateCommand _MaintenanceCommand;
        public DelegateCommand MaintenanceCommand =>
            _MaintenanceCommand ?? (_MaintenanceCommand = new DelegateCommand(MaintenanceCommandMethod));

        private DelegateCommand _CancelMaintenanceCommand;
        public DelegateCommand CancelMaintenanceCommand =>
            _CancelMaintenanceCommand ?? (_CancelMaintenanceCommand = new DelegateCommand(CancelMaintenanceCommandMethod));




        /// <summary>
        /// 刷新
        /// </summary>
        private DelegateCommand _RefreshCommand;
        public DelegateCommand RefreshCommand =>
            _RefreshCommand ?? (_RefreshCommand = new DelegateCommand(RefreshCommandMethod));




        /// <summary>
        /// 更新
        /// </summary>
        private DelegateCommand _UpdateCommand;
        public DelegateCommand UpdateCommand =>
            _UpdateCommand ?? (_UpdateCommand = new DelegateCommand(UpdateCommandMethod));


        /// <summary>
        /// 上传版本
        /// </summary>
        private DelegateCommand _UpLoadCommand;
        public DelegateCommand UpLoadCommand =>
            _UpLoadCommand ?? (_UpLoadCommand = new DelegateCommand(UpLoadCommandMethod));


        /// <summary>
        /// 上传日志
        /// </summary>
        private DelegateCommand _UpLogsCommand;
        public DelegateCommand UpLogsCommand =>
            _UpLogsCommand ?? (_UpLogsCommand = new DelegateCommand(UpLogsCommandMethod));


        private DelegateCommand _GoLogsControlCommand;
        public DelegateCommand GoLogsControlCommand =>
            _GoLogsControlCommand ?? (_GoLogsControlCommand = new DelegateCommand(GoLogsControlCommandMethod));

  


        /// <summary>
        /// Quit
        /// </summary>
        private DelegateCommand _QuitCommand;
        public DelegateCommand QuitCommand =>
            _QuitCommand ?? (_QuitCommand = new DelegateCommand(QuitCommandMethod));


        /// <summary>
        /// Quit
        /// </summary>
        private DelegateCommand _StartCommand;
        public DelegateCommand StartCommand =>
            _StartCommand ?? (_StartCommand = new DelegateCommand(StartCommandMethod));


        private DelegateCommand _SetServerAddressCommand;
        public DelegateCommand SetServerAddressCommand =>
            _SetServerAddressCommand ?? (_SetServerAddressCommand = new DelegateCommand(USetServerAddressMethod));




        /// <summary>
        /// 
        /// </summary>
        private DelegateCommand _UpdateServerAddressCommand;
        public DelegateCommand UpdateServerAddressCommand =>
            _UpdateServerAddressCommand ?? (_UpdateServerAddressCommand = new DelegateCommand(UpdateServerAddressMethod));




        #endregion

        public IndexPageViewModel(IContainerExtension container) : base(container)
        {

        }

        public override void ExecuteLoadedCommand()
        {
            base.ExecuteLoadedCommand();
            CurrentItemIndex = new Dictionary<int, int>();
            DeviceList =new ObservableCollection<DeviceDbModel>();
            GetAllCount();
            
        }

        public override void ExecuteUnLoadedCommand()
        {
            base.ExecuteUnLoadedCommand();
        }

        private  void ExecutePageUpdatedCommand(int? JumpIndex)
        {
            GetCurrentPageDevice(JumpIndex.Value, PageItemsCount);
        }

        /// <summary>
        /// 维护
        /// </summary>
        private async void MaintenanceCommandMethod()
        {
            try
            {
                if (SelectDeviceModel == null)
                {
                    MessageControl.Warning("请选择要操作的设备!", "RootMessageTooken");
                    return;
                }
                CommonStaticModel.LastCmdType = "维护命令";
                await SendCmd(SelectDeviceModel.deviceid, Convert.ToInt32(CmdSendType.Maintenance));
                RefreshCommandMethod();
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "GetAllCount", ex.Message);
            }
        }

        private async void CancelMaintenanceCommandMethod()
        {
            try
            {
                if (SelectDeviceModel == null)
                {
                    MessageControl.Warning("请选择要操作的设备!", "RootMessageTooken");
                    return;
                }
                CommonStaticModel.LastCmdType = "取消维护命令";
                await SendCmd(SelectDeviceModel.deviceid, Convert.ToInt32(CmdSendType.Cancel));
                RefreshCommandMethod();
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "GetAllCount", ex.Message);
            }
        }

        /// <summary>
        /// 刷新
        /// </summary>
        private void RefreshCommandMethod()
        {
            GetAllCount();
            GetCurrentPageDevice(1, PageItemsCount);
        }

        /// <summary>
        /// 跟新
        /// </summary>
        private  async void UpdateCommandMethod()
        {
            try
            {
                if (SelectDeviceModel==null) 
                {
                    MessageControl.Warning("请选择要操作的设备!", "RootMessageTooken");
                    return;
                }

                if (SelectDeviceModel.SelectFileDbModel==null) 
                {
                    MessageControl.Warning("请选择要升级的版本!", "RootMessageTooken");
                    return;
                }
                if (SelectDeviceModel.cmdtype== Convert.ToInt32(CmdSendType.Update)) 
                {
                    MessageControl.Warning("请先升级命令执行完成再继续操作!", "RootMessageTooken");
                    return;
                }
                CommonStaticModel.LastCmdType = "更新命令";
                await SendCmd(SelectDeviceModel.deviceid,Convert.ToInt32(CmdSendType.Update), SelectDeviceModel.SelectFileDbModel.uuid, SelectDeviceModel.SelectFileDbModel.filename);
                RefreshCommandMethod();
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "GetAllCount", ex.Message);
            }
        }

        private async void QuitCommandMethod()
        {
            try
            {
                if (SelectDeviceModel == null)
                {
                    MessageControl.Warning("请选择要操作的设备!", "RootMessageTooken");
                    return;
                }
                CommonStaticModel.LastCmdType = "退出命令";
                await SendCmd(SelectDeviceModel.deviceid, Convert.ToInt32(CmdSendType.close));
                RefreshCommandMethod();
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "GetAllCount", ex.Message);
            }
        }


        private async void StartCommandMethod()
        {
            if (SelectDeviceModel == null)
            {
                MessageControl.Warning("请选择要操作的设备!", "RootMessageTooken");
                return;
            }
            await SendCmd(SelectDeviceModel.deviceid, Convert.ToInt32(CmdSendType.Start));
            RefreshCommandMethod();
        }

        private void USetServerAddressMethod()
        {
            if (SelectDeviceModel == null)
            {
                MessageControl.Warning("请选择要操作的设备!", "RootMessageTooken");
                return;
            }
            Application.Current?.Dispatcher.BeginInvoke(new Action(() => {
                LayDialogParameter dialogParameter = new LayDialogParameter();
                dialogParameter.Add("deviceid", SelectDeviceModel.deviceid);
                LayDialogControl.Show(SystemResource.Nav_DialogBySetNewServerAddress, dialogParameter, rest =>
                {
                    RefreshCommandMethod();
                }, SystemResource.Nav_RootDialogTooken);
            }));
        }

        private  async void UpdateServerAddressMethod()
        {
            if (SelectDeviceModel == null)
            {
                MessageControl.Warning("请选择要操作的设备!", "RootMessageTooken");
                return;
            }
            await SendCmd(SelectDeviceModel.deviceid, Convert.ToInt32(CmdSendType.ChangeIpAddress));
            RefreshCommandMethod();
        }

        private void UpLoadCommandMethod()
        {
            if (SelectDeviceModel==null) 
            {
                MessageControl.Warning("请选择要操作的设备!", "RootMessageTooken");
                return;
            }
            Application.Current?.Dispatcher.BeginInvoke(new Action(() => {
                LayDialogParameter dialogParameter = new LayDialogParameter();
                dialogParameter.Add("deviceid", SelectDeviceModel.deviceid);
                LayDialogControl.Show(SystemResource.Nav_DialogByUplodFile, dialogParameter, rest =>
                {
                    RefreshCommandMethod();
                }, SystemResource.Nav_RootDialogTooken);
            }));
        }

        private void UpLogsCommandMethod()
        {
            if (SelectDeviceModel == null)
            {
                MessageControl.Warning("请选择要操作的设备!", "RootMessageTooken");
                return;
            }
            Application.Current?.Dispatcher.BeginInvoke(new Action(() => {
                LayDialogParameter dialogParameter = new LayDialogParameter();
                dialogParameter.Add("deviceid", SelectDeviceModel.deviceid);
                LayDialogControl.Show(SystemResource.Nav_DialogByTimeSelect, dialogParameter, rest =>
                {
                    RefreshCommandMethod();
                }, SystemResource.Nav_RootDialogTooken);
            }));
        }

        private void GoLogsControlCommandMethod()
        {
            if (this.SelectDeviceModel==null)
            {
                MessageControl.Warning("请选择要操作的设备!", "RootMessageTooken");
                return;
            }
            ToTargetConfigPage(SystemResource.Nav_LogsControlView);
        }
        private void ToTargetConfigPage(string _PagName)
        {
            NavigationParameters itemParameter = new NavigationParameters();
            itemParameter.Add("deviceid", this.SelectDeviceModel.deviceid);
            itemParameter.Add("DeviceIpAddress", this.SelectDeviceModel.ipaddress);
            Application.Current?.Dispatcher.Invoke(() => {
                Region.RequestNavigate(SystemResource.Nav_MainContent, _PagName, itemParameter);
            });
        }

        private Task SendCmd(string deviceid, int _cmd, string _filduuid = "", string _fileName = "") 
        {
            return Task.Run(async () => {
                string apiUrl = $"http://192.168.0.41:8081/api/ToSendCmd?_deviceid={deviceid}&_cmd={_cmd}&_filduuid={_filduuid}&_fileName={_fileName}";
                using (HttpClient client = new HttpClient())
                {
                    string postData = "";
                    HttpContent httpContent = new StringContent(postData);
                    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    httpContent.Headers.ContentType.CharSet = "utf-8";

                    HttpResponseMessage response = await client.PostAsync(apiUrl, httpContent);

                    if (response.IsSuccessStatusCode)
                    {
                        var read = response.Content.ReadAsStringAsync();
                        read.Wait();
                        ResponseBody json = JsonConvert.DeserializeObject<ResponseBody>(read.Result);
                        if (json.Code == ErrorCode.OK)
                        {
                            MessageControl.Warning("操作成功!", "RootMessageTooken");
                            SelectDeviceModel.cmdtype = Convert.ToInt32(CmdSendType.Maintenance);
                        }
                        else
                        {
                            MessageControl.Warning("操作失败!", "RootMessageTooken");
                            LogManager.WriteLog(LogTypeEnum.Exception, "UpdateCommandMethod", json.Data.ToString());
                        }
                    }
                    else
                    {
                        MessageControl.Warning("操作失败!", "RootMessageTooken");
                    }
                }
            });
        }

        private async void GetAllCount()
        {
            try
            {

                string apiUrl = $"http://192.168.0.41:8081/api/GetAllCountDevice";
                using (HttpClient client = new HttpClient())
                {
                    HttpResponseMessage response = await client.GetAsync(apiUrl);

                    if (response.IsSuccessStatusCode)
                    {
                        var read = response.Content.ReadAsStringAsync();
                        read.Wait();
                        ResponseBody json = JsonConvert.DeserializeObject<ResponseBody>(read.Result);
                        if (json.Data != null)
                        {
                            PageCount = Convert.ToInt32(json.Data);
                            PageItemsCount = Limits.FirstOrDefault();
                        }
                    }
                    else
                    {
                        Console.WriteLine("下载失败: " + response.ReasonPhrase);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "GetAllCount", ex.Message);
            }
        }

        private  void GetCurrentPageDevice(int _inputpageCode,int _inputPageSize) 
        {
            GetAllDevices(_inputpageCode, _inputPageSize);
           
        }

        private async void GetAllDevices(int _inputpageCode, int _inputPageSize) 
        {
            try
            {
                if (this.SelectDeviceModel!=null) 
                {
                    LastSelectDevId = this.SelectDeviceModel.deviceid;
                    if (this.SelectDeviceModel.SelectFileDbModel!=null) 
                    {
                        LastSelectFileId = this.SelectDeviceModel.SelectFileDbModel.uuid;
                    }
                }               
                DeviceList.Clear();
                string apiUrl = $"http://192.168.0.41:8081/api/GetCurrentPageDevice?_inputpageCode={_inputpageCode}&_inputPageSize={_inputPageSize}";
                using (HttpClient client = new HttpClient())
                {
                    HttpResponseMessage response = await client.GetAsync(apiUrl);

                    if (response.IsSuccessStatusCode)
                    {
                        var read = response.Content.ReadAsStringAsync();
                        read.Wait();
                        ResponseBody json = JsonConvert.DeserializeObject<ResponseBody>(read.Result);
                        if (json.Data != null)
                        {
                            List<DeviceDbModel> devList = JsonConvert.DeserializeObject<List<DeviceDbModel>>(json.Data.ToString());
                            if (devList.Count > 0)
                            {
                                int _index = 1;
                                foreach (var item in devList)
                                {
                                    item.Index = _index;
                                    DeviceList.Add(item);
                                    _index++;
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("下载失败: " + response.ReasonPhrase);
                    }
                }
                GetTargetFiles();
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "GetCurrentPageDevice", ex.Message);
            }
        }

        private async void GetTargetFiles() 
        {
            try
            {
                if (DeviceList.Count>0) 
                {
                    foreach (var item in DeviceList) 
                    {
                        string apiUrl = $"http://192.168.0.41:8081/api/GetAllFileVersion?_deviceid={item.deviceid}";
                        using (HttpClient client = new HttpClient())
                        {
                            HttpResponseMessage response = await client.GetAsync(apiUrl);

                            if (response.IsSuccessStatusCode)
                            {
                                var read = response.Content.ReadAsStringAsync();
                                read.Wait();
                                ResponseBody json = JsonConvert.DeserializeObject<ResponseBody>(read.Result);
                                if (json.Data != null)
                                {
                                    List<FileDbModel> fileList = JsonConvert.DeserializeObject<List<FileDbModel>>(json.Data.ToString());
                                    if (fileList.Count > 0)
                                    {
                                        item.FileList = new ObservableCollection<FileDbModel>();
                                        foreach (var itemFile in fileList)
                                        {

                                            item.FileList.Add(itemFile);
                                            
                                        }
                                    }
                                }
                            }
                            else
                            {
                                Console.WriteLine("下载失败: " + response.ReasonPhrase);
                            }
                        }
                    }

                    this.SelectDeviceModel = DeviceList.Where(p => p.deviceid == LastSelectDevId).FirstOrDefault();
                    if (this.SelectDeviceModel!=null) 
                    {
                        if (this.SelectDeviceModel.FileList!=null) 
                        {
                            this.SelectDeviceModel.SelectFileDbModel = this.SelectDeviceModel?.FileList.Where(p => p.uuid == LastSelectFileId).FirstOrDefault();
                        }
                    }
                    
                }
               
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypeEnum.Exception, "GetTargetFiles", ex.Message);
            }
        }

    }
}
